import axios from 'axios';
import {
  Toast,
} from 'vant';
import {router} from '@/router.js';
import storage from '@/model/storage'

// axios 配置

const http = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    'Accept-Language' : "zh-cn",
  },
  transformRequest: [function (data, headers) {
    var userToken = storage.get('userToken');
    headers['token'] = userToken;
    if(headers['Content-Type'] != 'application/json'){
      return data
    }else{
      return JSON.stringify(data);
    }
  }]
});

// 请求拦截器
http.interceptors.request.use(config => {
  config.loading ? Toast.loading({
    message: '加载中...',
    forbidClick: true,
    duration:0,
  }) : "";
  // 开发环境下，如果请求是 post,put,patch,则打印数据体，方便调试
  if (process.env.NODE_ENV === 'development') {
    const { method } = config;
    if (method === 'post' || method === 'put' || method === 'patch') {
      //console.log(config.data);
    }
  }
  return config;
}, error => {
  Toast.clear();
  return Promise.reject(error);
});

// 响应拦截器
http.interceptors.response.use(res => {
  Toast.clear();
  return res.data;
}, error => {
  Toast.clear();
  if (error && error.response) {
    let {config} = error.response;
    switch (error.response.status) {
      // 401 token失效
      case 401:
        router.replace({
          path: '/login',
        });
        break;
      
      // 403 服务器拒绝访问
      case 403:
       
        break;
      
      // 404 访问的资源不存在
      case 404:
        
        break;
      
      // 500 服务器错误
      case 500:
        Toast(`Server-- 500--`+config.url)
        break;
    }
    return Promise.reject(error);
  }
});

export default http;
